package com.anysoft.user;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.anysoft.HostConstant;
import com.anysoft.MentorConst;
import com.anysoft.R;
import com.anysoft.base.BaseActivity;
import com.anysoft.bean.BaseBean;
import com.anysoft.me.callback.StringDialogCallback;
import com.anysoft.utils.CommonUtil;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.MentorLogger;
import com.anysoft.utils.RSACryptographyUtil;
import com.anysoft.utils.StringUtils;
import com.anysoft.view.dialog.IcbcDialog;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class EditUserPwdActivity extends BaseActivity {
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.leftButton)
    Button leftButton;
    @BindView(R.id.tv_error_msg)
    TextView tv_error_msg;

    @BindView(R.id.et_old_pwd)
    EditText et_old_pwd;
    @BindView(R.id.et_new_pwd)
    EditText et_new_pwd;
    @BindView(R.id.et_confirm_pwd)
    EditText et_confirm_pwd;
    @BindView(R.id.btn_confirm_edit)
    Button btn_confirm_edit;

    /**
     * 新输入的密码是否合规
     */
    private boolean newPwdIsCompliance = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_user_pwd);
        ButterKnife.bind(this);
        title.setText("修改密码");
        et_new_pwd.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                newPwdIsCompliance = false;
                if (!hasFocus) {

                    String new_pwd = et_new_pwd.getText().toString().trim();//新密码
                    if (!StringUtils.isNullOrEmpty(new_pwd)) {
                        checkPassword();
                    }
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @OnClick({R.id.leftButton, R.id.btn_confirm_edit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.leftButton:
                finish();
                break;
            case R.id.btn_confirm_edit:
                save();
                break;
        }
    }

    /**
     * 校验密码是否合规
     */
    private void checkPassword() {
        Map<String, String> params = new HashMap<>();
        String newPwd = et_new_pwd.getText().toString().trim();//新密码
        String rsaKey = getRsaKey();
        String newPwdEncode = "";
        if (!TextUtils.isEmpty(rsaKey)) {
            newPwdEncode = RSACryptographyUtil.encryptByPublicKey(newPwd, rsaKey);
        }
        params.put("type", "1");//类型
        params.put("certificateNo", mentorApplication.accountLoginBean.getData().getIdentityNo());//证件号码
        params.put("password", newPwdEncode);//新密码

        OkGo.<String>post(HostConstant.CHECK_PASSWORD)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        MentorLogger.LogJson(TAG + "校验密码是否合规:", response.body());
                        parseJson_CheckPwd(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    /**
     * 修改密码
     */
    private void save() {
        if (!dataCheck()) {
            return;
        }
        String rsaKey = getRsaKey();
        String sOldPwd = et_old_pwd.getText().toString().trim();
        String sNewPwd = et_new_pwd.getText().toString().trim();
        String sConfirmPwd = et_confirm_pwd.getText().toString().trim();
        String sOldPwdEncode = RSACryptographyUtil.encryptByPublicKey(sOldPwd, rsaKey);
        String sNewPwdEncode = RSACryptographyUtil.encryptByPublicKey(sNewPwd, rsaKey);
        Map<String, String> params = new HashMap<>();
        params.put("token", mentorApplication.userBean.getToken());//
        params.put("oldPassword", sOldPwdEncode);//原交易密码
        params.put("newPassword", sNewPwdEncode);//新更改的密码
        params.put("certificateNo", mentorApplication.accountLoginBean.getData().getIdentityNo());//证件号

        Logger.t("-----CHANGE_PASSWORD-----").d(HttpUtils.createRequestUrl(this, HostConstant.CHANGE_PASSWORD, params));
        OkGo.<String>post(HostConstant.CHANGE_PASSWORD)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseJson(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast(MentorConst.INTERNET_ERROR);
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private boolean dataCheck() {
        String sOldPwd = et_old_pwd.getText().toString().trim();
        String sNewPwd = et_new_pwd.getText().toString().trim();
        String sConfirmPwd = et_confirm_pwd.getText().toString().trim();
        if (sOldPwd == null || "".equals(sOldPwd)) {
            showErrorMsg("请输入原密码");
            return false;
        }
        if (sNewPwd == null || "".equals(sNewPwd)) {
            showErrorMsg("请输入新密码");
            return false;
        }
        if (sConfirmPwd == null || "".equals(sConfirmPwd)) {
            showErrorMsg("请输入确认密码");
            return false;
        }
        if (!sNewPwd.equals(sConfirmPwd)) {
            showErrorMsg("新密码与确认密码不相同");
            return false;
        }
        if (!newPwdIsCompliance) {
            showErrorMsg("请输入合规密码");
            return false;

        }

        return true;
    }

    /**
     * 解析校验密码是否合规接口返回的数据
     *
     * @param response
     */
    private void parseJson_CheckPwd(String response) {
        BaseBean bean;
        try {
            bean = new Gson().fromJson(response, BaseBean.class);
        } catch (Exception exception) {
            showConfirmAlert(this, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(this, bean, response)) {
            return;
        }
        newPwdIsCompliance = true;
    }

    private void parseJson(String json) {
        BaseBean bean;
        try {
            bean = new Gson().fromJson(json, BaseBean.class);
        } catch (Exception exception) {
            showErrorMsg("数据解析异常，请联系管理员");
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, json)) {
            return;
        }
        if (!"0000".equals(bean.getRespCode())) {
            showErrorMsg(bean.getRespMsg());
            return;
        }

        clearUserPwd(mentorApplication.accountLoginBean.getData().getIdentityNo());
        setResult(RESULT_OK);

        IcbcDialog dialog = new IcbcDialog(mActivity);
        dialog.setAnimationEnable(true);
        dialog.setCancelable(false);
        dialog.setTitle("提示");
        dialog.setContentText("密码修改成功");
//                dialog.setContentText("该产品超过了您的风险承受能力，是否继续交易？");
        dialog.setEditTextType(false);
        dialog.setPositiveListener("确定", new IcbcDialog.OnPositiveListener() {
            @Override
            public void onClick(IcbcDialog dialog) {
                dialog.dismiss();
                finish();
            }
        }).show();
    }

    private void showErrorMsg(String msg) {
        if (StringUtils.isNullOrEmpty(msg)) {
            return;
        }
        showConfirmAlert(mActivity, msg + "");
    }
}
